<?php

namespace app\support;

use Illuminate\Pagination\LengthAwarePaginator;
use think\helper\Arr;

/**
 * 分页列表数据容器
 */
class ListContainer
{
    protected array $data;
    protected string $dataName;
    protected LengthAwarePaginator $paginator;

    public function __construct(LengthAwarePaginator $paginator, \Closure $iteration = null, $dataName = 'records')
    {
        $this->data = $paginator->items();
        $this->dataName = $dataName;
        $this->paginator = $paginator;
        // 有闭包执行闭包
        if ($iteration) {
            foreach ($this->data as $i => $rs) {
                $this->data[$i] = $iteration($rs);
            }
        }
    }

    public function getData(): array
    {
        return $this->data;
    }


    public function toArray(array $appends = []): array
    {
        return array_merge([
            $this->dataName => $this->data,
            'total' => $this->paginator->total(),
        ], $appends);
    }
}